package com.web.app.ctrl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.web.app.dao.ResourceMapper;
import com.web.app.pojo.Resource;
import com.web.app.util.MyFileUtil;
import com.web.app.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

/**
 * <p>
 * 资源管理表 前端控制器
 * </p>
 *
 * @author 林
 * @since 2022-09-21
 */
@RestController
@CrossOrigin
public class ResourceController {

    @Autowired
    private ResourceMapper resourceMapper;

    /**
     * 目的 ：根据班级的id信息 得到该班级底下所有的资源信息
     * @param resource
     * @return
     */
    @RequestMapping("/getResourcesList")
    public ResultUtil getResourcesList(Resource resource){
        ResultUtil resultUtil = ResultUtil.ok();
        QueryWrapper<Resource> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("relation_class_id",resource.getRelationClassId());
        if(resource.getRelationTeacherId() != null){
            queryWrapper.eq("relation_teacher_id",resource.getRelationTeacherId());
        }
        List<Resource> resources = resourceMapper.selectList(queryWrapper);
        resultUtil.setData(resources);
        return resultUtil;
    }

    @RequestMapping("/addResource")
    public ResultUtil addResource(MultipartFile file, Resource resource){
        ResultUtil resultUtil = ResultUtil.ok();
        if(resource.getResourceType() == 0){
            String url = MyFileUtil.fileUpload("resources", file);
            resource.setResourceUrl(url);
        }
        resourceMapper.insert(resource);
        return resultUtil;
    }

    @RequestMapping("/delResource")
    public ResultUtil delResource(Resource resource){
        ResultUtil resultUtil = ResultUtil.ok();
        if(resource.getResourceType() == 0){
            //把该路径下的文件删除
            System.out.println(resource.getResourceUrl());
            File file = new File(MyFileUtil.BASE_URL + "\\" + resource.getResourceUrl());
            file.delete();
        }
        resourceMapper.deleteById(resource.getId());
        return resultUtil;
    }
}

